<template>
    <div class="detail" v-if="spread" slot="content">
        <page-title :title="spread.name"></page-title>

        <div class="niupixian" v-if="spread.content && spread.content.relations && spread.content.relations.length>0">
            <swiper height="2rem" :duration="500" :interval="5000" :show-dots="false" :loop="true" :auto="true" class="scr-swiper" ref="lsswiper">
                <swiper-item v-for="(item, index) in spread.content.relations" :key="index">
                    <a :href="'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx42a449a1b9469d3b&redirect_uri=http://wechat-api.pryun.com.cn/api/oauth2outlink?'+item.link+'&response_type=code&scope=snsapi_userinfo&state=ysfb#wechat_redirect'">
                        <img :src="item.thumb+ '?imageMogr2/interlace/1/thumbnail/!200x150r/crop/200x150'">
                        <div class="title">
                            <span>
                                {{item.title}}
                            </span>
                        </div>
                    </a>
                </swiper-item>
            </swiper>
        </div>
        <div style="min-height:calc(100vh - 4.2rem);">
            <article class="article">
                <div class="dt-header">
                    <h2>{{spread.name}}</h2>
                    <p class="dt-info">
                        <span class="date">
                            <span>{{spread.release_time.replace(/-/g,'/') | formatTime('y-m-d h:i')}}</span>
                        </span>
                    </p>
                </div>
                <div class="rich-ctx" v-html="spread.rich_ctx">
                </div>
            </article>
            <div class="ms-box spread-list-box" v-if="spread.content.newsRelatedImg.length>0">
                <p class="title" v-if="spread.content.newsRelatedImg.length>0">
                    <i class="iconfont icon-image-frame"></i> 相关图片</p>
                <ul class="ms-box-list">
                    <li v-for="(item,i) in spread.content.newsRelatedImg" :key="i" @click="openImgDialog(i, spread.content.newsRelatedImg)" class="ms-list-img">
                        <div class="ac-image" :style="{backgroundImage:'url(' + item.url.replace(/ /g,'%20') + '?imageMogr2/interlace/1/thumbnail/!200x150r/crop/200x150' + ')'}"></div>
                        <div class="name">
                            <b>{{item.name}}</b>
                        </div>
                        <!-- <span class="size">{{item.fileSize}}</span> -->
                        <span class="download">
                            <i class="iconfont icon-arrow-right"></i>
                        </span>
                    </li>
                </ul>
            </div>
            <div v-if="spread.content.newsAttachment.length>0" class="about-list dt-accessory">
                <p class="title" v-if="spread.content.newsAttachment.length>0">
                    <i class="iconfont icon-accessory"></i> 附件</p>
                <ul v-if="spread.content.newsAttachment.length>0">
                    <li v-for="(item,index) in spread.content.newsAttachment" :key="index" class="about-list-li">
                        <a :href="item.url" class="about-list-li-link">{{item.name}}</a>
                        <i class="iconfont icon-arrow-right"></i>
                    </li>
                </ul>
                <ul v-if="spread.content.newsLink">
                    <li class="about-list-li">
                        <a :href="spread.content.newsLink">阅读原文</a>
                    </li>
                </ul>
            </div>

            <!-- 签名 -->
            <div class="about-list dt-accessory" v-if="spread.signature && spread.signature.length!=0">
                <p class="title">
                    <i class="iconfont icon-about"></i> 新闻背景</p>
                <div class="signature-title">{{spread.signatureTitle}}</div>
                <div v-if="spread.signature" class="signature" v-html="spread.signature">
                </div>
            </div>

            <div class="about-list comment" v-if="spread.comment_status==1">
                <p class="title" v-if="spreadCommentList && spreadCommentList.length!=0">
                    <span>
                        <i class="iconfont icon-zan"></i>
                        精选评论
                    </span>
                </p>
                <span v-if="wwuid" @click="addNewComment" class="dt-comment">
                    <i class="iconfont icon-edit"></i>写评论
                </span>
                <ul>
                    <li class="comment-list" v-if="!spreadCommentList || spreadCommentList.length==0">
                        <!-- <p class="username">暂无评论</p> -->
                    </li>
                    <li v-else v-for="(item,index) in spreadCommentList" :key="index" class="comment-list">
                        <div class="l">
                            <img v-if="item.user_headimg" :src="item.user_headimg" class="headimg">
                            <img v-else src="/static/images/noheadimg.png" class="headimg">
                        </div>
                        <div class="r">
                            <p class="username">{{item.user_name}}</p>
                            <p class="content">{{item.content}}</p>
                            <p class="system" v-if="item.reply">
                                <span></span>管理员回复 </p>
                            <p class="reply" v-if="item.reply">{{item.reply}}</p>
                        </div>
                    </li>
                </ul>
            </div>
            <!-- 附件图片预览 -->
            <div v-transfer-dom>
                <!-- v-if 为必要条件，否则会导致图片比例属性无效，无法计算出有效高度，导致页面空白 -->
                <x-dialog v-model="showXimg" class="dialog-img" hide-on-blur @on-hide="hideXdialog">
                    <div @click="hideXdialog" class="close">
                        <i class="iconfont icon-close"></i>
                    </div>
                    <swiper v-model="showImg" :show-dots="false" height="100%">
                        <swiper-item class="swiper-demo-img" v-for="(item, index) in showImgItem" :key="index">
                            <img :src="item.url">
                        </swiper-item>
                    </swiper>
                </x-dialog>
            </div>
            <div v-transfer-dom>
                <popup v-model="commentSendVisible" height="100%" style="background-color:#f6f6f6;padding:0.5rem">
                    <div class="popup1" style="margin-top: 15%">
                        <h3>{{spread.name}}</h3>
                        <group>
                            <x-textarea v-model="comment" placeholder="请输入评论内容"></x-textarea>
                        </group>
                        <flexbox class="invite-btn" style="margin-top: 5%">
                            <flexbox-item>
                                <x-button type="primary" @click.native="doSend" :disabled="onSending || !comment" action-type="button">发送</x-button>
                            </flexbox-item>
                            <flexbox-item>
                                <x-button @click.native="commentSendVisible = false">取消</x-button>
                            </flexbox-item>
                        </flexbox>
                    </div>
                </popup>
            </div>
            <!-- 激励区域 -->
            <div class="i-b" v-if="!shareUserId && showExciteBar">
                <!-- 抽奖 -->
                <div class="i-bd i-b-money" v-if="lotteryList.length>0" @click="doLottery">
                    <div class="i-br i-br-red">
                        <i class="iconfont icon-award"></i>
                        <span class="ibd-num">{{lotteryList.length}}</span>
                    </div>
                </div>
                <!-- 红包 -->
                <div class="i-bd i-b-thks" v-if="redpackList.length>0" @click="doRedpack">
                    <div class="i-br i-br-green">
                        <i class="iconfont icon-award2"></i>
                        <span class="ibd-num">{{redpackList.length}}</span>
                    </div>
                </div>
            </div>
        </div>
        <footerbar ref="footbar" @replyReaded="replyReaded" @sendEmail="sendEmail" @arrival="arrival" @consult="consult" :bottomShow="spread.bottom_show" :bottomData="spread.bottom_data" :onSendingEmail="onSendingEmail" :replyReadedCount="replyReadedCount" :linkman="spread.news_linkman_ids" :id="id" :shareUserId="shareUserId" :gainId="spread.gain_id"></footerbar>
    </div>
</template>

<script>
import { XDialog, TransferDomDirective as TransferDom, Swiper, SwiperItem, Popup, Cell, XButton, Flexbox, FlexboxItem, Group, XInput, Toast, Loading, XTextarea } from 'vux'
import Footerbar from '@/components/Footerbar'
import { getSpreadById, recordSpreadData, getSpreadComment, saveSpreadComment, sendEmail } from '@/api/spread.js'
import { findNSeenExcite, doExcite } from '@/api/excite.js'
import Cookies from 'js-cookie'

function getQV(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) { return pair[1]; }
    }
    return '';
}

export default {
    data() {
        return {
            eid: this.$route.query.eid,
            //传播ID
            id: this.$route.query.id,
            uid: this.$route.query.uid,
            wwuid: this.$route.query.wwuid,
            //分享者ID
            shareUserId: this.$route.query.shareUserId,
            shareType: this.$route.query.shareType,
            showQrcode: false,
            showXimg: false,
            showImg: null,
            showImgItem: null,
            show7: false,
            replyReadedCount: 0,
            spread: null,
            spreadCommentList: [],
            comment: null,
            commentSendVisible: false,
            //发送状态标识
            onSending: false,
            onSendingEmail: false,
            redpackList: [],
            lotteryList: [],
            showExciteBar: false,
        }
    },
    directives: {
        TransferDom
    },
    components: {
        Footerbar,
        XDialog,
        Swiper,
        SwiperItem,
        Popup,
        Cell,
        Group,
        XInput,
        Flexbox,
        FlexboxItem,
        XButton,
        Toast,
        Loading,
        XTextarea
    },
    methods: {
        // 抽奖
        doLottery() {
            this.$refs.footbar.duang(2, { lotteryList: this.lotteryList }, (lottery) => {
                doExcite('lottery', lottery.id)
            })
        },
        // 红包
        doRedpack() {
            let redpack = this.redpackList[0]
            this.$refs.footbar.duang(3, { redpack: redpack })
            doExcite('redpack', redpack.id)
            this.redpackList.splice(0, 1)
        },
        // 打开图片附件弹窗内容
        openImgDialog(i, array) {
            this.showXimg = true
            this.showImg = i
            this.showImgItem = array
        },
        // 关闭附件图片预览
        hideXdialog() {
            this.showXimg = false
            this.showImg = null
        },
        //评论对话框
        addNewComment() {
            // 置空评论内容
            this.comment = ''
            this.commentSendVisible = true
        },
        //发送新评论到后台
        doSend() {
            let _this = this
            this.$vux.confirm.show({
                title: '确认信息',
                content: '您已确认以上信息并且提交么？',
                onConfirm() {
                    _this.$vux.loading.show()
                    _this.onSending = true
                    saveSpreadComment(_this.comment, _this.id).then(res => {
                        _this.commentSendVisible = false
                        _this.onSending = false
                        _this.$vux.loading.hide()
                        if (res.spreadComment.status == 0) {
                            _this.$vux.toast.text('发送成功,审核成功后可显示在下方评论区')
                        } else if (!res.spreadComment.user_id) {
                            _this.$vux.toast.text('发送成功！（由于您未绑定该微信企业号，评论将以匿名的形式显示。）')
                        }
                        // 记录评论数据
                        recordSpreadData(_this.id, 1, _this.shareUserId).then(resp => {
                            if (resp.excite.integralList && resp.excite.integralList.length > 0) {
                                let integral = 0
                                resp.excite.integralList.forEach(item => {
                                    integral += item.integral
                                })
                                _this.$refs.footbar.duang(1, { integral: integral })
                            }
                            if (resp.excite.redpackList && resp.excite.redpackList.length > 0) {
                                _this.redpackList = _this.redpackList.concat(resp.excite.redpackList)
                            }
                            if (resp.excite.lotteryList && resp.excite.lotteryList.length > 0) {
                                let validLotteryList = resp.excite.lotteryList.filter(item => {
                                    return !item.end_time || +new Date(item.end_time.replace(/-/g, '/')) >= +new Date()
                                })
                                _this.lotteryList = _this.lotteryList.concat(validLotteryList)
                            }
                        }).catch(_ => { })
                        // 获取评论列表(前10条)
                        getSpreadComment(_this.id).then(resp => {
                            _this.spreadCommentList = resp.list
                        }).catch(_ => { })
                    }).catch(() => {
                        _this.onSending = false
                        _this.$vux.loading.hide()
                    })
                }
            })
        },
        // 回复看过
        replyReaded() {
            this.replyReadedCount++
            // 记录回复看过数据
            recordSpreadData(this.id, 3, this.shareUserId).then(resp => {
                this.replyReadedCount++
                if (resp.excite.integralList && resp.excite.integralList.length > 0) {
                    let integral = 0
                    resp.excite.integralList.forEach(item => {
                        integral += item.integral
                    })
                    this.$refs.footbar.duang(1, { integral: integral })
                }
                if (resp.excite.redpackList && resp.excite.redpackList.length > 0) {
                    this.redpackList = this.redpackList.concat(resp.excite.redpackList)
                }
                if (resp.excite.lotteryList && resp.excite.lotteryList.length > 0) {
                    let validLotteryList = resp.excite.lotteryList.filter(item => {
                        return !item.end_time || +new Date(item.end_time.replace(/-/g, '/')) >= +new Date()
                    })
                    this.lotteryList = this.lotteryList.concat(validLotteryList)
                }
            }).catch(_ => { })
        },
        // 发我邮箱
        sendEmail(email, uid) {
            if (email) {
                // 验证邮箱格式
                var reg = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
                if (!reg.test(email)) {
                    this.$vux.toast.show({
                        type: 'cancel',
                        time: 2000,
                        text: '邮箱地址<br/>格式不正确'
                    })
                    return false
                }
                this.onSendingEmail = true
                sendEmail(email, this.id, this.shareUserId, uid).then(res => {
                    this.$vux.toast.show({
                        type: 'success',
                        time: 3000,
                        text: '发送成功!<br/>邮件可能延迟送达，请耐心等候!'
                    })
                    this.onSendingEmail = false
                    // 记录发我邮箱数据
                    if (this.wwuid != null) {
                        recordSpreadData(this.id, 6, this.shareUserId).then(resp => {
                            if (resp.excite.integralList && resp.excite.integralList.length > 0) {
                                let integral = 0
                                resp.excite.integralList.forEach(item => {
                                    integral += item.integral
                                })
                                this.$refs.footbar.duang(1, { integral: integral })
                            }
                            if (resp.excite.redpackList && resp.excite.redpackList.length > 0) {
                                this.redpackList = this.redpackList.concat(resp.excite.redpackList)
                            }
                            if (resp.excite.lotteryList && resp.excite.lotteryList.length > 0) {
                                let validLotteryList = resp.excite.lotteryList.filter(item => {
                                    return !item.end_time || +new Date(item.end_time.replace(/-/g, '/')) >= +new Date()
                                })
                                this.lotteryList = this.lotteryList.concat(validLotteryList)
                            }
                        }).catch(_ => { })
                    }
                }).catch(_ => {
                    this.onSendingEmail = false
                })
            } else {
                this.$vux.toast.show({
                    type: 'cancel',
                    time: 2000,
                    text: '邮箱地址<br/>不能为空'
                })
            }
        },
        // 到店
        arrival() {
            this.$router.push({ path: '/mktStore', query: { source: this.id, eid: this.$route.query.eid, wwuid: this.wwuid, shareUserId: this.$route.query.shareUserId } });
        },
        // 咨询
        consult() {
            this.$router.push({ path: '/mktConsult', query: { source: this.id, eid: this.$route.query.eid, wwuid: this.wwuid, shareUserId: this.$route.query.shareUserId } });
        },
    },
    mounted() {
        this.$vux.loading.show()
        // 查询传播详情
        getSpreadById(this.id, this.shareUserId).then(async res => {
            this.uid = res.uid
            this.replyReadedCount = res.replyReadedCount
            this.spread = res.spread
            if (this.spread && this.spread.content) {
                this.spread.content = JSON.parse(this.spread.content)
                this.spread.content.relations.forEach((ele, i) => {
                    this.spread.content.relations[i].link = encodeURIComponent('tokenGenerator=' + this.spread.content.relations[i].link + '&appId=wx42a449a1b9469d3b&r=http://wx.pryun.com.cn/wechatNewsLetterLink')
                });
            }
            this.$vux.loading.hide()

            if (this.spread) {
                if (this.uid) {
                    // 获取未领取的激励
                    await findNSeenExcite(1, this.id, this.uid).then(resp => {
                        this.redpackList = this.redpackList.concat(resp.redpackList)
                        let validLotteryList = resp.lotteryList.filter(item => {
                            return !item.end_time || +new Date(item.end_time.replace(/-/g, '/')) >= +new Date()
                        })
                        this.lotteryList = this.lotteryList.concat(validLotteryList)
                    }).catch(_ => { })
                }

                if (this.wwuid) {
                    if (!this.shareUserId) {
                        // if (getQV('from') && getQV('from') == 'timeline') {
                        //     // 记录扩散阅读数据
                        //     recordSpreadData(this.id, 9, this.shareUserId, 8, 'timeline').catch(_ => { })
                        // } else {
                        // 记录点击阅读数据
                        await recordSpreadData(this.id, 2, this.shareUserId).then(resp => {
                            if (resp.excite.integralList && resp.excite.integralList.length > 0) {
                                let integral = 0
                                resp.excite.integralList.forEach(item => {
                                    integral += item.integral
                                })
                                this.$refs.footbar.duang(1, { integral: integral })
                            }
                            if (resp.excite.redpackList && resp.excite.redpackList.length > 0) {
                                this.redpackList = this.redpackList.concat(resp.excite.redpackList)
                            }
                            if (resp.excite.lotteryList && resp.excite.lotteryList.length > 0) {
                                let validLotteryList = resp.excite.lotteryList.filter(item => {
                                    return !item.end_time || +new Date(item.end_time.replace(/-/g, '/')) >= +new Date()
                                })
                                this.lotteryList = this.lotteryList.concat(validLotteryList)
                            }
                        }).catch(_ => { })
                        // }
                    } else {
                        if (this.eid != 106) {
                            // 记录扩散阅读数据
                            recordSpreadData(this.id, 9, this.shareUserId, this.shareType).catch(_ => { })
                        } else {
                            if (!Cookies.get(this.wwuid + '_' + this.shareUserId + '_' + this.id)) {
                                recordSpreadData(this.id, 9, this.shareUserId, this.shareType).catch(_ => { })
                                var exp = new Date();
                                exp.setTime(exp.getTime() + 7 * 24 * 60 * 60 * 1000);//过期时间 7天
                                Cookies.set(this.wwuid + '_' + this.shareUserId + '_' + this.id, 1, { expires: exp })
                            } else {
                                console.log(this.wwuid + '_' + this.shareUserId + '_' + this.id + '。已贡献扩散阅读，不能重复贡献')
                            }
                        }
                    }
                }

                // 如果只有一个红包或者抽奖那么直接弹出
                if (this.redpackList.length == 1) {
                    this.doRedpack()
                }
                if (this.lotteryList.length > 0) {
                    this.doLottery()
                }

                //稍等一会显示激励区域
                setTimeout(() => {
                    this.showExciteBar = true
                }, 100)

                // 获取评论列表(前10条)
                getSpreadComment(this.id).then(resp => {
                    this.spreadCommentList = resp.list
                }).catch(_ => { })

                // 获取微信分享参数(同步)
                let shareParams = {
                    title: this.spread.share_title ? this.spread.share_title : this.spread.name,
                    desc: this.spread.share_remarks ? this.spread.share_remarks : this.spread.name,
                    imgUrl: this.spread.share_thumburl
                }
                this.wxShareSync(res.wxShareConfig, shareParams,
                    (type) => {
                        this.$vux.toast.text('分享成功')
                        // 记录转发分享数据
                        recordSpreadData(this.id, type, this.shareUserId).then(resp => {
                            if (resp.excite.integralList != null && resp.excite.integralList.length > 0) {
                                let integral = 0
                                resp.excite.integralList.forEach(item => {
                                    integral += item.integral
                                })
                                this.$refs.footbar.duang(1, { integral: integral })
                            }
                            if (resp.excite.redpackList != null && resp.excite.redpackList.length > 0) {
                                this.redpackList = this.redpackList.concat(resp.excite.redpackList)
                            }
                            if (resp.excite.lotteryList != null && resp.excite.lotteryList.length > 0) {
                                let validLotteryList = resp.excite.lotteryList.filter(item => {
                                    return !item.end_time || +new Date(item.end_time.replace(/-/g, '/')) >= +new Date()
                                })
                                this.lotteryList = this.lotteryList.concat(validLotteryList)
                            }
                            // 如果只有一个红包或者抽奖那么直接弹出
                            if (this.redpackList.length == 1) {
                                this.doRedpack()
                            }
                            if (this.lotteryList.length > 0) {
                                this.doLottery()
                            }
                            //稍等一会显示激励区域
                            setTimeout(() => {
                                this.showExciteBar = true
                            }, 100)
                        }).catch(_ => {
                        })
                    })
            }
        }).catch(_ => {
            this.$vux.loading.hide()
        })
    }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
.popup {
    width: 100%;
    height: 100%;
}
.niupixian {
    position: fixed;
    top: 0;
    height: 2rem;
    width: 100%;
    background-color: #fff;
}
</style>
